package com.hnucm.cooklife.custom.loading;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class MyLoading extends View {
    private Paint mCirclePaint;
    private Paint mWhiteCirclePaint;
    private Paint mMoonPaint;
    private AnimatorSet animatorSet;

    private int color;

    public void setColor(int color) {
//        mCirclePaint.setColor(color);
        invalidate();
    }

    // 控件中心点坐标
    private int cvX, cvY;

    public MyLoading(Context context) {
        super(context);
    }

    public MyLoading(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //关键这里要initPaint()
        initPaint();
    }

    public MyLoading(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    private void initPaint(){
        mCirclePaint = new Paint();
        mCirclePaint.setColor(Color.BLACK);
        mCirclePaint.setStyle(Paint.Style.FILL);
        mCirclePaint.setAntiAlias(true);

        mWhiteCirclePaint = new Paint();
        mWhiteCirclePaint.setColor(Color.WHITE);
        mWhiteCirclePaint.setStyle(Paint.Style.FILL);
        mWhiteCirclePaint.setAntiAlias(true);

        mMoonPaint = new Paint();
        mMoonPaint.setColor(Color.BLACK);
        mMoonPaint.setStyle(Paint.Style.FILL);
        mMoonPaint.setAntiAlias(true);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        cvX = getMeasuredWidth() / 2;
        cvY = getMeasuredHeight() / 2;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        RectF mOvalRecf = new RectF(cvX - 100,cvY - 60,cvX + 100,cvY + 60);
        canvas.drawOval(mOvalRecf,mCirclePaint);
//        mCirclePaint.setColor(Color.BLACK);
//        canvas.drawOval(mOvalRecf,mCirclePaint);

        canvas.drawCircle(cvX,cvY,40,mWhiteCirclePaint);

        //画月亮
        canvas.drawCircle(cvX,cvY,20,mMoonPaint);
        double sqrt = Math.sqrt(2);
        float f = (float)sqrt;
        canvas.drawCircle(cvX + 20 / f,cvY - 20 / f,20,mWhiteCirclePaint);
    }


    public void stopAnimator(){
        animatorSet.cancel();
    }

    public void startAnimator(){
        animatorSet = new AnimatorSet();
        animatorSet.playTogether(mRotateAnimator,mChangeAnimator);
        animatorSet.setDuration(2000);
        animatorSet.start();
    }

    ObjectAnimator mRotateAnimator = ObjectAnimator.ofFloat(this,"rotation",0,360);
    ObjectAnimator mChangeAnimator = ObjectAnimator.ofInt(this,"color",
            Color.BLACK,Color.GRAY);

}
